
from .models import *
import json
from .verify import *
import re
from django.shortcuts import render
from django.http import HttpResponse

from django.views.decorators.csrf import csrf_exempt        # 调取装饰器，单独取消csrf_token

# Create your views here.

"""
    学科      Subject     subject_text
    科目      Course      course_text     关联学科
    班级      Grade       grade_text      关联科目（多对多关系，用的through方法重建关系）
    职务      Duty        duty_text
"""


@verify_control
def api_add_subject(request):
    """
        @author: 董海明
        @date:  2018-11-7
        本接口为前端新建学科，用post提交数据
        需要用到的参数：{"sub_text": "xxx"}
    """
    info = dict(request.POST)
    try:
        Subject.objects.get(subject_text=info["sub_text"][0])
    except Subject.DoesNotExist:
        Subject.objects.create(subject_text=info["sub_text"][0])
        return HttpResponse(json.dumps({"message": "添加成功"}))
    else:
        return HttpResponse(json.dumps({"message": "该学科已经存在，不需要重得添加"}))


@verify_control
def api_change_subject(request):
    """
        @author:董海明
        @date: 2018-11-7
        本接口为修改学科，用post提交数据
        需要用到的参数：{"old_sub_text": "xxx", "new_sub_text": "xxx"}

    """
    info = dict(request.POST)
    try:
        sub_text = Subject.objects.get(subject_text=info["old_sub_text"][0])
    except Subject.DoesNotExist:
        return HttpResponse(json.dumps({"message": "输入的学科不存在，请重新输入"}))
    else:
        sub_text.update(subject_text=info["new_sub_text"][0])
        return HttpResponse(json.dumps({"message": "修改成功"}))


@verify_control
def api_del_subject(request):
    """
        @author:董海明
        @ date: 2018-11-10
        本接口为删除学科，只有空学科才可以删除，请谨慎操作
        需要提交的数据 {"del_sub_text": "xxx"}
    """
    info = dict(request.POST)
    try:
        sub_ject = Subject.objects.get(subject_text=info["del_sub_text"][0])
    except Subject.DoesNotExist:
        return HttpResponse(json.dumps({"message": "输入的学科不存在，请重新输入"}))
    else:
        course_list = sub_ject.course_set.all()
        if len(course_list) == 0:
            sub_ject.delete()
            return HttpResponse(json.dumps(({"message": "删除成功"})))
        else:
            return HttpResponse(json.dumps({"message": "该学科不为空，不允许删除"}))


def api_find_subject(request):
    """
        @author: 董海明
        @ date: 2018-11-10
        本接口为查找学科，
        查找所有的学科
        本接口为网页上返回一个字典{"id": "xx","subject_text": "xxx"}
    """
    find_subject = Subject.objects.all().value()
    return HttpResponse(json.dumps({"message": find_subject}))


@verify_control
def api_add_course(request):
    """
        @author: 董海明
        @ date: 2018-11-15
        本接口为添加科目
        需要传入的数据有{"sub_text": "xxx", "course": "xxx"}

    """
    info = dict(request.POST)
    try:
        sub_text = Subject.objects.get(subject_text=info["sub_text"][0])
    except Subject.DoesNotExist:
        return HttpResponse(json.dumps({"message": "输入的学科不存在，请重新输入"}))
    else:
        try:
            course_name = Course.objects.get(course_text=info["course"][0])
        except Course.DoesNotExist:
            sub_text.course_set.create(course_text=course_name)
            return HttpResponse(json.dumps({"message": "录入成功"}))
        else:
            return HttpResponse(json.dumps({"message": "此科目已经存在，不需要重复添加"}))


@verify_control
def api_change_course(request):
    """
        @author: 董海明
        @date:2018-11-15
        本接口为修改科目名称
        需要传入的数据：{"old_course": "xxx", "new_course": "xxx"}
    """
    info = dict(request.POST)
    try:
        course_name = Course.objects.get(course_text=info["old_course"][0])
    except Course.DoesNotExist:
        return HttpResponse(json.dumps({"message": "输入的科目名称不存在，请重新输入"}))
    else:
        try:
            new_course_name = Course.objects.get(course_text=info["new_course"][0])
        except Course.DoesNotExist:
            course_name.create(course_text=new_course_name)
            return HttpResponse(json.dumps({"message": "修改成功"}))
        else:
            return HttpResponse(json.dumps({"message": "存在相同的名称，请重新输入"}))


@verify_control
def api_change_course_sub(request):
    """
        @author:董海明
        @date:2018-11-15
        本接口为修改科目所在的学科
        需要的数据：{"course": "xxx", "sub_text": "xxx"}
    """
    pass


@verify_control
def api_del_course(request):
    """
        @author:董海明
        @date: 2018-11-15
        本接口为删除科目，请谨慎操作
        需要的数据 ：{"course": "xxx"}
    """
    info = dict(request.POST)
    try:
        course_name = Course.objects.get(course_text=info["course"][0])
    except Course.DoesNotExist:
        return HttpResponse(json.dumps({"message": "输入的科目不存在，请重新输入"}))
    else:
        grade_list = course_name.grade_set.all()
        if len(grade_list) == 0:
            course_name.delete()
            return HttpResponse(json.dumps({"message": "删除成功"}))
        else:
            return HttpResponse(json.dumps({"message": "本科目不为空，不能删除"}))


@verify_control
def api_find_course(request):
    """
        @author: 董海明
        @date: 2018-11-16
        本接口为查找科目，按学科查询
        需要的数据{"sub_text": "xxx"}
    """
    info = dict(request.POST)
    try:
        sub_text = Subject.objects.get(subject_text=info["sub_text"][0])
    except Subject.DoesNotExist:
        return HttpResponse(json.dumps({"message": "输入的科目不存在，请重新输入"}))
    else:
        course_dict = sub_text.course_set.all().values()
        return HttpResponse(json.dumps({"message": course_dict}))


@verify_control
def api_find_course_name(request):
    """
        @author: 董海明
        @date: 2018-11-16
        本接口为查找科目，按科目名称查找
        需要提交的数据为{"course": "xxx"}
    """
    info = dict(request.POST)
    try:
        course = Course.objects.get(course_text=info["course"][0])
    except Course.DoesNotExist:
        return HttpResponse(json.dumps({"message": "输入的科目不存在，请重新输入"}))
    else:
        return HttpResponse(json.dumps({"message": course}))


@verify_control
def api_add_grade(request):
    """
        @author:董海明
        @date:2018-11-16
        本接口为添加班级，按科目添加班级
        需要用到的数据：{"course":"xxx","grade_name": "xxx"}
    """
    info = dict(request.POST)
    try:
        course = Course.objects.get(course_text=info["course"][0])
    except Course.DoesNotExist:
        return HttpResponse(json.dumps({"message": "输入的科目不存在，请重新输入"}))
    else:
        course.grade_set.create(grade_text=info["grade_name"][0])
        return HttpResponse(json.dumps({"message": "班级添加成功"}))


@verify_control
def api_change_grade(request):
    """
        @author:董海明
        @date:2018-11-16
        本接口为调整班级状态，
        需要用到的数据：{"grade_name": "xxx"}
    """
    info = dict(request.POST)
    try:
        grade = Grade.objects.get(grade_text=info["grade_name"][0])
    except Grade.DoesNotExist:
        return HttpResponse(json.dumps({"message": "输入的班级不存在，请重新输入"}))
    else:
        grade.grade_status = 0
        return HttpResponse(json.dumps({"message": "状态修改成功"}))


@verify_control
def api_change_grade_course(request):
    """
        @author: 董海明
        @date:  2018-11-19
        本接口为修改班级对应的科目，比如原来是pyhon初级，调整以后为python高级
        需要用到的数据{"grade": "xxx", "new_course": "xxx"}
    """
    info = dict(request.POST)
    try:
        grade = Grade.objects.get(grade_text=info["grade_name"][0])
    except Grade.DoesNotExist:
        return HttpResponse(json.dumps({"message": "输入的班级不存在，请重新输入"}))
    else:
        try:
            course = Course.objects.get(course_text=info["new_course"][0])
        except Course.DoesNotExist:
            return HttpResponse(json.dumps({"message": "输入的科目不存在，请重新输入"}))
        else:
            grade.update(course_code=course)
            return HttpResponse(json.dumps({"message": "更新成功"}))


@verify_control
def api_del_grade(request):
    """
        @author:董海明
        @date:2018-11-16
        本接口为删除班级，请谨慎操作
        需要用到的数据：{"grade_name": "xxx"}
    """
    info = dict(request.POST)
    try:
        grade = Grade.objects.get(grade_text=info["grade_name"][0])
    except Grade.DoesNotExist:
        return HttpResponse(json.dumps({"message": "输入的班级不存在，请重新输入"}))
    else:
        grade.delete()
        return HttpResponse(json.dumps({"message": "删除成功"}))


@verify_control
def api_find_grade(request):
    """
        @author:董海明
        @date:2018-11-16
        本接口为按科目，查找班级
        需要提交的数据为{"course": "xxx"}
    """
    info = dict(request.POST)
    try:
        course_name = Course.objects.get(course_text=info["course"][0])
    except Course.DoesNotExist:
        return HttpResponse(json.dumps({"message": "输入入的科目不存在"}))
    else:
        grade_name = course_name.grade_set.all()
        return HttpResponse(json.dumps({"message": grade_name}))


@verify_control
def api_add_duty(request):
    """
        @author:董海明
        @date:2018-11-17
        本接口为添加职务
        需要提交的数据{"duty_name" : "xxx"}
    """
    info = dict(request.POST)
    try:
        Duty.objects.get(duty_text=info["duty_name"][0])
    except Duty.DoesNotExist:
        Duty.objects.create(duty_text=info["duty_name"][0])
        return HttpResponse(json.dumps({"message": "添加成功"}))
    else:
        return HttpResponse(json.dumps({"message": "该职务已经存在"}))


@verify_control
def api_change_duty(request):
    """
        @author:董海明
        @date:2018-11-19
        本接口为修改职务状态
        需要提交的数据{"duty_name": "xxx"}
    """
    info = dict(request.POST)
    try:
        duty = Duty.objects.get(duty_text=info["duty_name"][0])
    except Duty.DoesNotExist:
        return HttpResponse(json.dumps({"message": "输入的职务不存在，请重新输入"}))
    else:
        duty.update(duty_status=0)
        return HttpResponse(json.dumps({"message": "状态修改成功"}))


@verify_control
def api_del_duty(request):
    """
        @author: 董海明
        @date: 2018-11-19
        本接口为删除职务，删除职务需要职务为空，才可以删除
        需要提交的数据 ：{"duty_name": "xxx"}
    """
    info = dict(request.POST)
    try:
        duty = Duty.objects.get(duty_text=info["duty_name"][0])
    except Duty.DoesNotExist:
        return HttpResponse(json.dumps({"message": "输入的职务不存在，请重新输入"}))
    else:
        if duty.duty_status == 0:
            duty.delete()
            return HttpResponse(json.dumps({"message": "删除成功"}))
        else:
            return HttpResponse(json.dumps({"message": "职务状态不为False,不可以删除"}))


@verify_control
def api_find_duty(request):
    """
        @author: 董海明
        @date:2018-11-19
        本接口为查找职务，

    """
    duty_list = Duty.objects.all().values()
    return HttpResponse(json.dumps({"message": duty_list}))


@verify_control
def api_add_user(request):
    """
        @author: 董海明
        @date: 2018-11-19
        本接口为添加用户的接口，
        需要提交的数据{"duty_name": "xxx", "grade_name": "xxx",  "user_code": "xxx","user": "xxx",
                        "pswd": "xxx", "id_code": "xxx", "phone": "xxx", "sex": "xxx"}
    """
    regex_id = "(^[1-9]\\d{5}(18|19|([23]\\d))\\d{2}((0[1-9])|(10|11|12))\
    (([0-2][1-9])|10|20|30|31)\\d{3}[0-9Xx]$)|(^[1-9]\\d{5}\\d{2}((0[1-9])|\
    (10|11|12))(([0-2][1-9])|10|20|30|31)\\d{2}$)"
    regex_phone = "^(((13[0-9])|(14[579])|(15([0-3]|[5-9]))|(16[6])|(17[0135678])|(18[0-9])|(19[89]))\\d{8})$"
    info = dict(request.POST)
    try:
        duty = Duty.objects.get(duty_text=info["duty_name"][0])
        grade = Grade.objects.get(grade_text=info["grade_name"][0])
        user_code = User.objects.get(user_name=info["user_code"][0])
    except Duty.DoesNotExist:
        return HttpResponse(json.dumps({"message": "输入的职务不存在，请重新输入"}))
    except Grade.DoesNotExist:
        return HttpResponse(json.dumps({"message": "输入的班级不存在，请重新输入"}))
    except User.DoesNotExist:
        id_info = re.search(regex_id, info["id_code"][0])
        phone = re.search(regex_phone, info["phone"][0])
        if id_info.group() != "" and phone.group() != "":
            duty.user_set.create(grade_code=grade.pk, user_code=user_code, user_name=info["user"][0],
                                 user_sex=info["sex"][0], user_identity=id_info.group(),
                                 user_phone=phone.group(), user_pwd=info["pswd"][0])
            return HttpResponse(json.dumps({"message": "添加成功"}))
        elif id_info.group() == "":
            return HttpResponse(json.dumps({"message": "身份证号格式输入不正确，请重新输入"}))
        elif phone.group() == "":
            return HttpResponse(json.dumps({"message": "手机号格式输入不正确，请重新输入"}))
    else:
        return HttpResponse({"message": "用户编码已经存在，请重新输入"})


@verify_control
def api_change_user_name(request):
    """
        @author: 董海明
        @date: 2018-11-19
        本接口为修改用户名，用户编号为唯一，所以只需要提交编号和新用户名
        需要提交的数据{"user_code": "xxx", "new_user_name": "xxx"}
    """
    info = dict(request.POST)
    try:
        user_obj = User.objects.get(user_name=info["user_code"][0])
    except User.DoesNotExist:
        return HttpResponse(json.dumps({"message": "输入的用户编码不正确，请重新输入"}))
    else:
        user_obj.update(user_name=info["new_user_name"][0])
        return HttpResponse(json.dumps({"message": "更新成功"}))


@verify_control
def api_change_user_duty(request):
    """
        @author: 董海明
        @date: 2018-11-19
        本接口为修改用户职务，由于工作岗位调动，需要作职位变动，用户编号为唯一，所以只需要提交编号和新职务名称
        需要提交的数据{"user_code": "xxx", "new_duty_name": "xxx"}
    """
    info = dict(request.POST)
    try:
        user_obj = User.objects.get(user_name=info["user_code"][0])
    except User.DoesNotExist:
        return HttpResponse(json.dumps({"message": "输入的用户编码不正确，请重新输入"}))
    else:
        duty_obj = Duty.objects.get(duty_text=info["new_duty_name"][0])
        user_obj.update(duty_code=duty_obj.pk)
        return HttpResponse(json.dumps({"message": "职务更新成功"}))


@verify_control
def api_change_user_phone(request):
    """
        @author: 董海明
        @date: 2018-11-19
        本接口为修改用户手机号,用户编号为唯一，所以只需要提交编号和新手机号
        需要提交的数据{"user_code": "xxx", "new_phone": "xxx"}
    """
    regex_phone = "^(((13[0-9])|(14[579])|(15([0-3]|[5-9]))|(16[6])|(17[0135678])|(18[0-9])|(19[89]))\\d{8})$"
    info = dict(request.POST)
    try:
        user_obj = User.objects.get(user_name=info["user_code"][0])
    except User.DoesNotExist:
        return HttpResponse(json.dumps({"message": "输入的用户编码不正确，请重新输入"}))
    else:
        new_phone = re.search(regex_phone, info["new_phone"][0])
        if new_phone != "":
            user_obj.update(user_phone=new_phone.group())
            return HttpResponse(json.dumps({"message": "用户手机更新成功"}))
        else:
            return HttpResponse(json.dumps({"message": "输入的手机号格式不正确，请重新输入"}))


@verify_control
def api_change_user_pswd(request):
    """
        @author: 董海明
        @ date: 2018-11-19
        本接口为修改用户的密码，编码唯一，所以只需要提供用户编码 和新密码就可以
        需要提交的数据{"user_code": "xxx", "new_pswd": ["xxx", "xxx"]}
    """
    info = dict(request.POST)
    try:
        user_obj = User.objects.get(user_name=info["user_code"][0])
    except User.DoesNotExist:
        return HttpResponse(json.dumps({"message": "输入的用户编码不正确，请重新输入"}))
    else:
        if info["new_pswd"][0] == info["new_pswd"][1]:
            user_obj.update(user_pwd=info["new_pswd"][0])
            return HttpResponse(json.dumps({"message": "密码修改成功"}))
        else:
            return HttpResponse(json.dumps({"message": "两次密码不一致，请重新输入"}))


@verify_control
def api_change_user_status(request):
    """
        @author: 董海明
        @date: 2018-11-19
        本接口为修改用户的状态，因为用户编码唯一，所以只需要提供用户编码和新的状态就可以
        需要提交的数据{"user_code": "xxx", "status": "0"}

    """
    info = dict(request.POST)
    try:
        user_obj = User.objects.get(user_name=info["user_code"][0])
    except User.DoesNotExist:
        return HttpResponse(json.dumps({"message": "输入的用户编码不正确，请重新输入"}))
    else:
        user_obj.update(account_status=info["status"][0])
        return HttpResponse(json.dumps({"message": "修改成功"}))


@verify_control
def api_change_user_sex(request):
    """
        @author: 董海明
        @date: 2018-11-19
        本接口为修改用户的性别，因为用户编码唯一，所以只需要提供用户编码和性别
        需要提交的数据{"user_code": "xxx", "sex": "xxx"}

    """
    info = dict(request.POST)
    try:
        user_obj = User.objects.get(user_name=info["user_code"][0])
    except User.DoesNotExist:
        return HttpResponse(json.dumps({"message": "输入的用户编码不正确，请重新输入"}))
    else:
        user_obj.update(user_sex=info["sex"][0])
        return HttpResponse(json.dumps({"message": "修改成功"}))


@verify_control
def api_change_user_id(request):
    """
        @author: 董海明
        @date: 2018-11-19
        本接口为修改用户的身份证号，因为用户编码唯一，所以只需要提供用户编码、手机号和新的身份证号
            身份信息为重要信息，需要验证手机号
        需要提交的数据{"user_code": "xxx","phone":"xxx", "id_code": "xxx"}

    """
    info = dict(request.POST)
    try:
        user_obj = User.objects.get(user_name=info["user_code"][0])
    except User.DoesNotExist:
        return HttpResponse(json.dumps({"message": "输入的用户编码不正确，请重新输入"}))
    else:
        regex_id = "(^[1-9]\\d{5}(18|19|([23]\\d))\\d{2}((0[1-9])|(10|11|12))\
        (([0-2][1-9])|10|20|30|31)\\d{3}[0-9Xx]$)|(^[1-9]\\d{5}\\d{2}((0[1-9])|\
        (10|11|12))(([0-2][1-9])|10|20|30|31)\\d{2}$)"
        regex_phone = "^(((13[0-9])|(14[579])|(15([0-3]|[5-9]))|(16[6])|(17[0135678])|(18[0-9])|(19[89]))\\d{8})$"
        phone = re.search(regex_phone, info["phone"][0])
        id_info = re.search(regex_id, info["id_code"][0])
        if phone.group() == User.objects.get(user_phone=info["phone"][0]):
            if id_info.group() != "":
                user_obj.update(user_identity=id_info.group())
                return HttpResponse(json.dumps({"message": "身份证更新成功"}))
            else:
                return HttpResponse(json.dumps({"message": "输入的身份信息格式不正确，请重新输入"}))
        else:
            return HttpResponse(json.dumps({"message": "手机号验证失败，请填写正确的手机信息"}))


@verify_control
def api_login(request):
    """
        @author: 董海明
        @date: 2018-11-7
        本接口为登陆接口, 提交数据方式为post
            需要传入的数据：{"user":"xxx", "pswd": "xxx"}
    """
    info = dict(request.POST)
    try:
        user_nm = User.objects.get(user_name=info["user"][0])
    except User.DoesNotExist:
        return HttpResponse(json.dumps({"message": "输入的用户名或密码不正确"}))
    else:
        if info["pswd"][0] == user_nm.user_pwd:
            return HttpResponse(json.dumps({"message": "登陆成功"}))
        else:
            return HttpResponse(json.dumps({"message": "输入的用户名或密码不正确"}))

